<template>
  <jke-modal :visible.sync="jkeForm.visible" :width="1200" :title="jkeForm.title" :fullscreen.sync="jkeForm.fullscreen"
    :switchFullscreen="jkeForm.switchFullscreen">
    <a-form-model ref="ruleForm" :model="formData" :rules="rules">
      <a-card title="工序信息" :bordered="false" style="margin-top: 12px">
        <a-row>
          <a-col :span="7">
            <a-form-model-item label="工单编号" style="width: 100%" prop="orderId">
              <a-select style="width: 100%" @change="handleChangeSelect" v-model="formData.orderId" placeholder="请选择">
                <a-select-option v-for="item in orderList" :value="item.id" :key="item.id">
                  {{ item.orderCode }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="1"></a-col>
          <a-col :span="7">
            <a-form-model-item label="生产物品" style="width: 100%">
              <a-input v-model="formData.goodsName" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="1"></a-col>
          <a-col :span="7">
            <a-form-model-item label="单位" style="width: 100%">
              <a-input v-model="formData.basicUnit" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="7">
            <!-- 生产任务的报工弹窗工序是直接回显，不可更改，生产报工的报工弹窗工序是可选的，根据情况渲染字段 -->
            <a-form-model-item label="工序" style="width: 100%" prop="processId">
              <a-select style="width: 100%" v-model="formData.processId" @change="changeProcess" placeholder="请选择">
                <a-select-option v-for="item in processesList" :value="item.id" :key="item.id">
                  {{ item.processesName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="1"></a-col>
          <a-col :span="7">
            <a-form-model-item label="计划数" style="width: 100%">
              <a-input v-model="formData.reportNum" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="1"></a-col>
          <a-col :span="7">
            <a-form-model-item style="width: 100%" prop="allocateType">
              <template #label>
                <span slot="label">
                  任务进度&nbsp;
                  <a-tooltip title="当前工序的计划数为：工单生产计划数量*当前工序报工配比">
                    <a-icon type="question-circle" />
                  </a-tooltip>
                </span>
              </template>
              <a-input v-model="progress" disabled />
              <a-progress :percent="percent" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="7">
            <a-form-model-item label="操作人" style="width: 100%">
              <a-input v-model="formData.reportNum" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="1"></a-col>
          <a-col :span="7">
            <a-form-model-item label="可报工数" style="width: 100%">
              <a-input v-model="formData.reportNum" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="1"></a-col>
          <a-col :span="7">

          </a-col>
        </a-row>
        <a-row>
          <a-col :span="7">
            <a-form-model-item label="合格数" style="width: 100%">
              <a-input-number style="width: 100%" v-model="formData.qualifiedNum" :min="0" />
            </a-form-model-item>
          </a-col>
          <a-col :span="1"></a-col>
          <a-col :span="7">
            <a-form-model-item label="不合格数" style="width: 100%">
              <a-input read-only style="width: 100%" v-model="formData.unqualifiedQuantityNum" :min="0"
                @click="selectNonconformingItem" />
            </a-form-model-item>
          </a-col>
          <a-col :span="1"></a-col>
          <a-col :span="7">
            <a-form-model-item label="报工时间" style="width: 100%">
              <a-date-picker style="width: 100%" v-model="formData.startValue" :disabled-date="disabledStartDate" show-time
                format="YYYY-MM-DD HH:mm:ss" placeholder="Start" @openChange="handleStartOpenChange" />
            </a-form-model-item>
          </a-col>
        
          <a-col :span="7">
            <a-form-model-item label="不合格原因" style="width: 100%">
              <a-input :value="formData.unqualifiedDtos.map((item) => item.unqualifiedName).toString()" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-card>
      <a-card title="自定义信息" :bordered="false" style="margin-top: 12px">
        <a-row>
          
        </a-row>

      </a-card>
    </a-form-model>
    <div class="footer-submit form-footer">
      <a-button @click="cancel" class="submitBtn" style="margin-right: 10px"> 取消</a-button>
      <a-button type="primary" :loading="loading" class="submitBtn" @click="onSubmit"> 提交</a-button>
    </div>

    <!--不合格项弹窗-->
    <a-modal v-model="nonConformanceVisible" title="不合格数输入" @ok="handleOk">
      <a-table row-key="unqualifiedId" :columns="disqualificationColumns" :pagination="false"
        :dataSource="disqualificationData">
        <div slot="index" slot-scope="text, record, index">
          {{ index + 1 }}
        </div>
        <div slot="customNum" slot-scope="text, record">
          <a-input v-model="record.customNum" placeholder="请输入" />
        </div>
      </a-table>
      <template slot="footer">
        <div style="display: flex; justify-content: space-between; align-items: center">
          <div>
            <span>不合格原因：{{ unqualifiedRows }}</span>，
            <span>不合格数：{{ unqualifiedNumber }}</span>
          </div>
          <div>
            <a-button key="back" @click="handleCancel"> 取消</a-button>
            <a-button key="submit" type="primary" :loading="loadingSubmit" @click="handleOk"> 确定</a-button>
          </div>
        </div>
      </template>
    </a-modal>
  </jke-modal>
</template>
<script>
import productionAPI from '@/api/productionOrder'
import FileUpload from '@/components/fileActions/FileUpload.vue'
import {
  productionReportingAdd,
  productionReportingEdit,
  getWorkOrderList,
  processByOrderId,
  processDetail,
  produceBatch,
} from '@/api/produce/productionManage'
import { unqualifiedList } from '@/api/quality/index'

export default {
  name: 'processChangeForm',
  components: { FileUpload },
  props: {
    rowData: {
      type: Object | null,
    },
  },
  data () {
    return {
      processesCodeList: [],
      processesList: [],
      visible: false,
      formData: {
        orderCode: undefined,
        processId: undefined,
        goodsName: '',
        spec: '',
        basicUnit: '',
        reportNum: '',
        planStartTime: '',
        deviceNames: '',
        processRequirements: '',
        processesName: '',
        unqualifiedNum: '',
        num: '',
        qualifiedNum: '', //合格数
        unqualifiedQuantityNum: '', //不合格数
        batchId: '', //批次
        unqualifiedDtos: [],
        operatorId: '',
        operator: [],
      },
      rules: {
        orderId: [{ required: true, message: '请选择工单编号', trigger: 'change' }],
        processId: [{ required: true, message: '请选择工序', trigger: 'change' }],
        operator: [
          // { required: true, message: '请选择操作人', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              if (this.formData.operator.length < 1) {
                callback(new Error('请选择！'))
              } else {
                callback()
              }
            },
            trigger: 'change',
          },
        ],
        num: [{ required: true, message: '报工数不能为空', trigger: 'change' }],
      },
      jkeForm: {
        title: '生产报工',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      loadingSubmit: false,
      loading: false,
      taskFlag: 0,
      orderList: [],
      batchDatas: [], //批次列表
      nonConformanceVisible: false,
      disqualificationData: [], //不合格项列表
      disqualificationColumns: [
        {
          title: '序号',
          ellipsis: true,
          dataIndex: 'index',
          scopedSlots: {
            customRender: 'index',
          },
        },
        {
          title: '不合格原因',
          ellipsis: true,
          dataIndex: 'unqualifiedName',
        },
        {
          title: '数量',
          dataIndex: 'customNum',
          scopedSlots: {
            customRender: 'customNum',
          },
        },
      ],
      disabledOperator: false,
      operatorDatas: [],
      processPlanNum: 0, //用于计算进度的计划数
      progressReportNum: 0, //用于计算进度的报工数
    }
  },
  async created () {
    this.initData()
  },
  methods: {
    async initData () {
      // 获取生产中的工单
      const WorkOrderRes = await getWorkOrderList({ status: 1, pageNo: 1, pageSize: 100000 })
      if (WorkOrderRes && WorkOrderRes.code == 200) {
        this.orderList = WorkOrderRes.result.records
      }

      // 获取不合格项
      const {
        result: { records },
      } = await unqualifiedList({ pageNo: 1, pageSize: 100000 })
      this.disqualificationData = (records || []).map((item, index) => ({
        customNum: '',
        unqualifiedId: item.id,
        unqualifiedName: item.unqualifiedName,
        index: index + 1,
      }))
    },
    // 工单选择字段改变
    async handleChangeSelect (value) {
      if (value) {
        const processRes = await processByOrderId({ id: value, processesType: 1 })
        if (processRes && processRes.code == 200) {
          this.processesList = processRes.result
        }
      } else {
        this.processesList = []
      }

      // 清空工序相关数据
      this.formData.processId = ''
      this.formData.goodsName = ''
      this.formData.goodsId = ''
      this.formData.spec = ''
      this.formData.basicUnit = ''
      this.formData.reportNum = 0
      this.formData.num = 0
      this.processPlanNum = 0
      this.formData.planStartTime = ''
      this.formData.planEndTime = ''
      this.formData.deviceNames = ''
      this.formData.processRequirements = ''
      this.formData.qualifiedNum = 0
      this.formData.unqualifiedNum = 0
    },
    // 根据获取工序详情
    async changeProcess (v) {
      const { result } = await processDetail({ id: v })
      if (result) {
        this.formData.goodsName = result.goodsName
        this.formData.goodsId = result.goodsId
        this.formData.spec = result.spec
        this.formData.basicUnit = result.basicUnit
        this.formData.reportNum = result.reportNum
        this.formData.num = result.num
        this.formData.planStartTime = result.planStartTime
        this.formData.planEndTime = result.planEndTime
        this.formData.deviceNames = result.deviceNames
        this.formData.processRequirements = result.processRequirements
        this.formData.qualifiedNum = result.reportNum
        this.formData.unqualifiedNum = result.unqualifiedNum
        this.processPlanNum = result.num
        this.progressReportNum = this.progressReportNum = Number(result.unqualifiedNum) + Number(result.qualifiedNum) //用于计算进度的报工数
      } else {
        this.formData.goodsName = ''
        this.formData.goodsId = ''
        this.formData.spec = ''
        this.formData.basicUnit = ''
        this.formData.reportNum = 0
        this.formData.num = 0
        this.processPlanNum = 0
        this.formData.planStartTime = ''
        this.formData.planEndTime = ''
        this.formData.deviceNames = ''
        this.formData.processRequirements = ''
        this.formData.qualifiedNum = 0
        this.formData.unqualifiedNum = 0
      }

      this.formData.batchId = ''

      // 获取操作人列表以及判断权限
      const operatorInfo = await productionAPI.getQueryOperator({ processId: v })
      this.operatorDatas = operatorInfo.result
      //isLeader为1时是负责人，可选择操作人,否则则不能更改
      //isOwn为是否为当前账户用户
      const hasOwnData = operatorInfo.result.find((item) => item.isOwn == 1) //是否为当前账户用户

      this.formData.operator.push(hasOwnData.userId)
      if (hasOwnData.isLeader == 1) {
        this.disabledOperator = false
      } else {
        this.disabledOperator = true
      }
      await this.getBatch()
    },

    async getBatch () {
      const { result } = await produceBatch({ processId: this.formData.processId, orderId: this.formData.orderId })
      this.batchDatas = result
    },

    initDetail (query) {
      this.jkeForm.visible = true
    },
    operatorChange (storeVals, row) {
      this.$forceUpdate()
    },
    onSubmit () {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.loading = true
          let form = JSON.parse(JSON.stringify(this.formData))
          if (form.operator) {
            form.operator = form.operator.join(',')
          }
          const { code, message } = await (this.formData.id ? productionReportingEdit : productionReportingAdd)(form)
          if (code === 200) {
            this.$antdMessage.success(message)
            this.jkeForm.visible = false
            this.$emit('confirm')
          } else {
            this.$antdMessage.error(message)
          }
          this.loading = false
        } else {
          return false
        }
      })
    },
    resetForm () {
      this.$refs.ruleForm.resetFields()
    },
    cancel () {
      this.jkeForm.visible = false
      this.$emit('confirm')
    },

    // 不合格项填写
    selectNonconformingItem (item, index) {
      this.nonConformanceVisible = true
    },
    handleCancel () {
      this.nonConformanceVisible = false
    },
    // 确认不合格项的填写
    handleOk () {
      let data = this.disqualificationData.filter((item) => item.customNum)
      if (data.length > 0) {
        this.formData.unqualifiedDtos = JSON.parse(JSON.stringify(data))
      }
      this.formData.unqualifiedQuantityNum = this.unqualifiedNumber
      this.handleCancel()
    },
    /* 获取附件 */
    getFileList (v) {
      this.formData.attachment = v
    },
  },
  computed: {
    // percent() {
    //   let num1 = this.formData.qualifiedNum ? this.formData.qualifiedNum : 0 //合格数
    //   let num2 = this.formData.unqualifiedNumber //不合格数
    //   let number = ((num1 + num2) / this.processPlanNum) * 100 * 100
    //   return Math.floor(number * 100) / 100
    // },
    // // (合格数+不合格数)/报工数
    // progress() {
    //   let num1 = this.formData.qualifiedNum ? this.formData.qualifiedNum : 0 //合格数
    //   let num2 = this.unqualifiedNumber //不合格数
    //   return Math.floor((num1 + num2) * 100) / 100 + '/' + Math.floor(this.processPlanNum * 100) / 100
    // },
    // 进度=(合格数+不合格数)/计划数
    percent () {
      let number = (this.progressReportNum / this.processPlanNum) * 100
      return Math.floor(number * 100) / 100
    },
    progress () {
      return Math.floor(this.progressReportNum * 100) / 100 + '/' + Math.floor(this.processPlanNum * 100) / 100
    },
    // 不合格项数量
    unqualifiedNumber () {
      return this.disqualificationData && this.disqualificationData.length > 0
        ? this.disqualificationData.reduce((num, item) => num + (Number(item.customNum) || 0), 0)
        : 0
    },
    // 不合格项项
    unqualifiedRows () {
      return this.disqualificationData.filter((item) => item.customNum).length
    },
  },
  watch: {
    'jkeForm.visible': function (val) {
      if (!val) {
        this.cancel()
      }
    },
    'formData.unqualifiedQuantityNum': function (val) {
      this.formData.num = (this.formData.qualifiedNum || 0) + (val || 0) || ''
    },
    'formData.qualifiedNum': function (val) {
      this.formData.num = (val || 0) + (this.formData.unqualifiedQuantityNum || 0) || ''
    },
  },
}
</script>
<style lang="less" scoped>
.auto-code-input {
  :deep(.ant-input) {
    border-right: 0px !important;
  }

  :deep(.ant-input-group-addon) {
    border-left: 0px !important;
  }
}

.flex(@jc, @ai, @fd: row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}

.form-body {
  height: calc(100vh - 100px);
  overflow-y: scroll;
}

.form-footer {
  position: absolute;
  bottom: 0;
  right: 0;
  padding-left: 100px;
  z-index: 2;
}

.submitBtn {
  .flex(flex-end, center);
  padding: 8px;
}

.code-btn {
  position: absolute;
  right: 0;
  top: -34.5px;
}

.mb20 {
  margin-bottom: 20px;
}
</style>
